package com.anyfo.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.anyfo.dao.ICommonDao;

public class CommonDaoImpl implements ICommonDao{
    ResultSet rs = null;   
    private HibernateTemplate hibernateTemplate;
    
	public Object get(Class c, String id) {
		return this.hibernateTemplate.get(c, id);
	}


	public boolean add(Object o) throws RuntimeException {
		try{
			this.hibernateTemplate.save(o); 
		}catch(Exception e){
			e.printStackTrace();
		}

		return true;

	}

	public boolean addByJDBC(String entityTable, String[] propertys,
			Object[] params) throws RuntimeException,SQLException, HibernateException {

		Session session = this.hibernateTemplate.getSessionFactory().openSession();
		Connection conn= session.connection();
		PreparedStatement ps = null;
		 StringBuffer insertSql =new StringBuffer("");   
	        if(null !=entityTable &&!entityTable.equals("")) {   
	            insertSql.append("INSERT INTO  ");
	        }else {   
	            return false;   
	        } 
	        if(null !=propertys && propertys.length >=1) {   
	            insertSql.append(entityTable.toLowerCase());   
	            insertSql.append("  (");   
	             for(int i= 0 ; i<propertys.length;i++) {   
	                 insertSql.append(propertys[i]);
	                 insertSql.append(",");   
	                 if(propertys[i].trim().toLowerCase().equals(entityTable.toLowerCase()+"id") && propertys[i]!=null) {
	                	 System.out.println("增加方法中的ObjectId的值必须是‘null’值causeby：（主键不能有重复值）");
	                     return false;   
	                 }   
	             }   
	             insertSql = new StringBuffer(insertSql.substring(0, insertSql.length()-1));   
	             insertSql.append(" )");   
	        }   
	        if(null !=params) {   
	            insertSql.append(" VALUES (");   
	             for(int i= 0 ; i<propertys.length;i++) {   
	                 if(params[i] != null) {   
	                     insertSql.append("'").append(params[i]).append("',");   
	                 }else {   
	                     insertSql.append(params[i]).append(",");   
	                 }   
	             }   
	             insertSql = new StringBuffer(insertSql.substring(0, insertSql.length()-1));   
	             insertSql.append(" ) ;");   
	        }   
	        System.out.println(insertSql.toString()); 
			ps = conn.prepareStatement(insertSql.toString());
			try {
				ps.execute();
			} catch (SQLException e) {
				
				e.printStackTrace();
				return false;
			}  
	        return true;   

	}

	public boolean del(Object o)  throws RuntimeException {
		this.hibernateTemplate.delete(o); 
		return true;
	}

	public boolean delByJDBC(String entityTable, String sqlWhere) throws SQLException {
		Session session = this.hibernateTemplate.getSessionFactory().openSession();
		Connection conn= session.connection();
		PreparedStatement ps = null;
		
		StringBuffer deleteSql = new StringBuffer("");    
        deleteSql.append("DELETE FROM  ");   
        deleteSql.append(entityTable.toLowerCase());   
        if(null != sqlWhere && !sqlWhere.equals("") &&sqlWhere.length()>1) {   
            if(sqlWhere.trim().split(" ")[0].toLowerCase().equals("where")){   
                deleteSql.append(sqlWhere);   
            }else {   
                deleteSql.append(" WHERE " ).append(sqlWhere);   
            }   
        }   
        System.out.println(deleteSql.toString());   
        ps = conn.prepareStatement(deleteSql.toString());
		try {
			ps.execute();
		} catch (SQLException e) {
			
			e.printStackTrace();
			return false;
		}  
        return true;   
	}

	public boolean isExist(String hql) throws RuntimeException  {
		List list = this.hibernateTemplate.find(hql);
		return (0 == list.size() ? false : true);

	}

	public ResultSet queryByJDBC(String entityTable, Object[] propertys,
			String sqlWhere) throws SQLException {
		
		Session session = this.hibernateTemplate.getSessionFactory().openSession();
		Connection conn= session.connection();
		PreparedStatement ps = null;
		
		StringBuffer querySql = new StringBuffer("");   
        if(null !=entityTable &&!entityTable.equals("") &&(null == propertys ||propertys.length<1)) {   
            querySql.append("SELECT * FROM ").append(entityTable.toLowerCase());   
        }else if(null !=entityTable &&!entityTable.equals("") &&(null != propertys ||propertys.length>=1)) {   
            if(null !=propertys && propertys.length >=1) {   
                querySql.append("SELECT  ");   
                 for(int i= 0 ; i<propertys.length;i++) {   
                     querySql.append(propertys[i]).append(",");   
                 }   
                 querySql = new StringBuffer(querySql.substring(0, querySql.length()-1));   
            }   
            querySql.append(" FROM ").append(entityTable.toLowerCase());   
        }   
        if(null != sqlWhere && !sqlWhere.equals("") &&sqlWhere.length()>1) {   
            if(sqlWhere.trim().split(" ")[0].toLowerCase().equals("where")){   
                querySql.append(sqlWhere);   
            }else {   
                querySql.append(" WHERE " ).append(sqlWhere);   
            }   
        }   
        System.out.println(querySql);   
        ps = conn.prepareStatement(querySql.toString());
		try {
			rs = ps.executeQuery();

		} catch (SQLException e) {
			
			e.printStackTrace();
			return null;
		}  
        return rs;  
	}

	public boolean update(Object o)  throws RuntimeException {
		this.hibernateTemplate.merge(o); 
		return true;
	}

	public boolean updateByJDBC(String entityTable, String[] propertys,
			Object[] params, String sqlWhere) throws SQLException {
		
		Session session = this.hibernateTemplate.getSessionFactory().openSession();
		Connection conn= session.connection();
		PreparedStatement ps = null;
		
		StringBuffer updateSql =new StringBuffer("");   
        if(null !=entityTable &&!entityTable.equals("")) {   
            updateSql.append("UPDATE ").append(entityTable.toLowerCase());   
        }else {   
            return false;   
        }   
        if(null !=propertys ) {   
            if(null !=params) {   
                if(propertys.length == params.length) {   
                    for(int i= 0 ; i<propertys.length;i++) {   
                        updateSql.append("  SET ");   
                        updateSql.append(propertys[i]).append("=").append("'").append(params[i]).append("',");   
                         if(propertys[i].trim().toLowerCase().equals(entityTable.toLowerCase()+"id")) {   
                             System.out.println("修改方法中的ObjectId的值不能被更新causeBy（主键唯一性）");  
                         }   
                    }   
                       
                    updateSql = new StringBuffer(updateSql.substring(0, updateSql.length()-1));   
                       
                    if(null != sqlWhere && !sqlWhere.equals("") &&sqlWhere.length()>1) {   
                        if(sqlWhere.trim().split(" ")[0].toLowerCase().equals("where")){   
                            updateSql.append(sqlWhere);   
                        }else {   
                            updateSql.append(" WHERE " ).append(sqlWhere);   
                        }   
                    }   
                }else{   
                    return false;   
                }   
            }   
        }     
        System.out.println(updateSql.toString());
        ps = conn.prepareStatement(updateSql.toString());
		try {
			ps.execute();
		} catch (SQLException e) {
			
			e.printStackTrace();
			return false;
		}  
        return true;   
	}

	public List<Object> useHQL(String hql) {
		List<Object> resultList = this.hibernateTemplate.find( hql );
		return resultList;
	}

	public List<Object> usePagingHql(String hql, Integer pageSize, Integer start) {
		Query q = this.hibernateTemplate.getSessionFactory().openSession().createQuery(hql);
		q.setFirstResult(start);
		q.setMaxResults(pageSize);
		List<Object> resultList = q.list();
		return resultList;
	}

	public ResultSet getRs() {
		return rs;
	}

	public void setRs(ResultSet rs) {
		this.rs = rs;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}


	public boolean saveOrUpdate(Object o) {
		this.hibernateTemplate.saveOrUpdate(o); 
		return true;
	}
}

